/*
 * @Author: wangchao
 * @Date: 2024-10-04 12:07:03
 * @LastEditors: wangchao
 * @LastEditTime: 2024-10-12 08:38:48
 * @FilePath: \JD-RTT-Driver\applications\u_utilits.c
 * @Description: 基础组件(utilits)
 * Copyright (c) 2024 by Bingshan Guardian, All Rights Reserved.
 */

#include "u_utilits.h"

rt_int16_t int16_abs(rt_int16_t x)
{
    // return x
    return (x < 0) ? -x : x;
}

rt_uint16_t median_filter_average_value(rt_uint16_t data[], rt_uint8_t len, rt_uint8_t abandon)
{
    // Insertion sort
    for (rt_uint8_t i = 1; i < len; i++)
    {
        rt_uint16_t key = data[i];
        rt_uint8_t j = i;
        while (j > 0 && data[j - 1] > key)
        {
            data[j] = data[j - 1];
            j--;
        }
        data[j] = key;
    }

    // Calculate the average after discarding the "abandon" number of smallest and largest values
    rt_uint32_t sum = 0;  // Use a larger type to avoid overflow
    rt_uint8_t valid_len = len - 2 * abandon;

    for (rt_uint8_t i = abandon; i < len - abandon; i++)
    {
        sum += data[i];
    }

    return sum / valid_len;  // Return the average
}
